<?php

class WPSPO_Users extends WPSPO_Object {

    /*
     * STATUT
     * 1 => Participant
     * 2 => Sponsor d'un participant
     *  */
    function save($user, $statut, $defi, $option = '', $newletter = 1) {
        global $wpdb;

        $data = array(
            'users_id_user' => $user,
            'users_id_statut' => 1,
            'users_id_defi' => $defi,
            'users_newletter' => $newletter,
            'users_option_value' => $option
        );
        $result = $wpdb->insert(WSPO_USERS, $data);
        if($result) {
            return true;
        }
    }
    
    function get_count($id) {
        global $wpdb;
        $count = $wpdb->get_var( $wpdb->prepare( "SELECT count(users_id) FROM ". WSPO_USERS . " WHERE users_id_defi = %d ", $id ) );
        if($count=='') { $count = 0; }
        return $count;
    }
    
    function get_countUserByDefi($id, $defi) {
        global $wpdb;
        $count = $wpdb->get_var( $wpdb->prepare( "SELECT count(users_id) FROM ". WSPO_USERS . " WHERE users_id_user = %d AND users_id_defi = %d ", $id, $defi) );
        return $count;
    }
    
    function get_listByDefi($id) {
        global $wpdb;
        if(!$id) { die('Aucun défi sélectionné');  }
        $result = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ". WSPO_USERS . " WHERE users_id_defi = %d ", $id), 'OBJECT' );
        if($result) {
            return $result;
        } 
    }
    
    function get_listByUser($id) {
        global $wpdb;
        if(!$id) { die('Aucun utilisateur sélectionné');  }
        $result = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ". WSPO_USERS . " WHERE users_id_user = %d ", $id), 'OBJECT' );
        if($result) {
            return $result;
        } 
    }
    
    function updateRealise($idDefi, $idUser, $num) {
        global $wpdb;
        $data = array(
            'users_realise' => $num
        );
        if(!$idUser) { die('Aucun utilisateur sélectionné');  }
        $where = array( 'users_id_defi' => $idDefi, 'users_id_user' => $idUser);
        $result = $wpdb->update(WSPO_USERS, $data, $where);
        if($result) {
            return true;
        }      
    }
    
    /*
     * Supprime un participant en particulier
     */
    function deleteUserByDefi($user, $id) {
		global $wpdb;
        // Supprime dans la table des promesses 'PREFIX_wpspo_promesse'
		$resultDelete =  $wpdb->query( $wpdb->prepare("DELETE FROM ". WSPO_USERS . " WHERE users_id_user = %d AND users_id_defi = %d LIMIT 1", $user, $id) );
		if($resultDelete) {
            return true;
        }
	}
    
}
